package com.lq.order.Interceptor;

import com.lq.common.util.UserContext;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 用户上下文拦截器
 * 用于从请求头中提取用户信息并存储到ThreadLocal中
 */
@Component
public class UserContextInterceptor implements HandlerInterceptor {
    
    /**
     * 在请求处理之前设置用户上下文
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        // 从请求头中获取用户ID
        String userId = request.getHeader("X-User-Id");
        if (userId != null && !userId.isEmpty()) {
            UserContext.setUserId(userId);
        }
        return true;
    }
    
    /**
     * 在请求处理完成后清理用户上下文
     * 防止内存泄漏
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
        UserContext.clear();
    }
}